var mongoose = require('mongoose')
var Test = mongoose.model('Test')
var Category = mongoose.model('Category')



// index page
exports.index = function(req, res ,next) {
  Test.find({})
    .populate('category', 'name')
    .exec(function(err, tests) {
      if (err) {
        console.log(err)
      }

   	  res.end(JSON.stringify(tests));
    })
    next()
}

// index page
exports.add = function(req, res) {

  var testObj={
  	  doctor: '德玛西亚',
	  title: '艾欧里亚',
	  language: '中文',
	  country: '中国',
	  summary: '草丛里跳出一个盖伦，送了把大宝剑给你！',
	  flash: 'lalala',
	  poster: 'www.bukengnikengshui.com',
	  category:0,
	  categoryName:'英雄联盟'
  }

  _test = new Test(testObj)

     var categoryId = testObj.category
     var categoryName = testObj.categoryName

    _test.save(function(err, test) {
      if (err) {
        console.log(err)
      }
      if (categoryId) {
        Category.findById(categoryId, function(err, category) {
          category.movies.push(test._id)

          category.save(function(err, category) {
             console.log('category: is ok')
             console.log(category)
          })
        })
      }
      else if (categoryName) {
        var category = new Category({
          name: categoryName,
          movies: [test._id]
        })

        category.save(function(err, category) {
          test.category = category._id
          test.save(function(err, test) {
             console.log('ok: ',test)
          })
        })
      }

    })
}